package com.jinchengll.xigua.ui.viewmodel;

import android.util.Log;

import androidx.lifecycle.MutableLiveData;

import com.jinchengll.xigua.entity.Page;
import com.jinchengll.xigua.entity.Video;
import com.jinchengll.xigua.network.base.BaseObserver;
import com.jinchengll.xigua.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * @author jinchengll
 * @since 2021/10/5
 */
public class RecommendViewModel extends BaseViewModel {

    private final String TAG = "RecommendViewModel";

    private int pageNo = 1;
    private int pageSize = 5;
    // 视频当前播放的位置
    public int mCurPos = -1;
    // 上次播放的位置，用于页面切回来之后恢复播放
    public int mLastPos = mCurPos;

    public MutableLiveData<List<Video>> videoListLD = new MutableLiveData<>();


    /**
     * 根据是否是刷新和加载更多来进行网络请求
     *
     * @param isRefresh 是否是刷新
     */
    public void getViewPage(boolean isRefresh) {
        // 如果是刷新，从第一页开始获取
        if (isRefresh) pageNo = 1;
        repository.getVideoPage(pageNo, pageSize, new BaseObserver<Page<Video>>() {
            @Override
            public void onSuccess(Page<Video> data) {
                List<Video> records = data.getRecords();
                if (records.size() == 0) {
                    ToastUtil.showShort("没有数据");
                    return;
                }
                List<Video> videoList = videoListLD.getValue();
                if (videoList == null) videoList = new ArrayList<>();
                // 如果是刷新，清空当前内容
                if (isRefresh) videoList.clear();
                videoList.addAll(records);
                videoListLD.setValue(videoList);
                pageNo = data.getCurrent() + 1;
            }

            @Override
            public void onFailure(String errorMsg) {
                Log.e(TAG, errorMsg);
                ToastUtil.showShort(errorMsg);
            }
        });
    }

}
